﻿using System;
using System.Globalization;
using System.Linq.Expressions;
using System.Threading;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using RHD.Common.Web.Utility.Extensions;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class DatepickerExtension {
		public static MvcHtmlString Datepicker(this HtmlHelper htmlHelper, string id, object value = null, object htmlAttributes = null) {
			return DatepickerInput(htmlHelper, id, value, null, htmlAttributes);
		}

		public static MvcHtmlString DatepickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) {
			ModelMetadata model = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
			return DatepickerInput(htmlHelper, ExpressionHelper.GetExpressionText(expression), model.Model, model, htmlAttributes);
		}

		private static MvcHtmlString DatepickerInput(HtmlHelper htmlHelper, string id, object value = null, ModelMetadata modelMetadata = null, object htmlAttributes = null) {
			TagBuilder input = new TagBuilder("input");
			input.GenerateId(id);
			input.Attributes["name"] = htmlHelper.GetFullHtmlFieldName(id);
			input.Attributes["type"] = "text";
			if (htmlAttributes != null)
				input.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));
			id = input.Attributes["id"];

			Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR");
			if (value != null)
				input.MergeAttribute("value", ((DateTime)value).ToShortDateString(), true);

			MvcHtmlString validation = MvcHtmlString.Empty;
			if (modelMetadata != null) {
				input.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(modelMetadata.PropertyName, modelMetadata));
				validation = ValidationExtensions.ValidationMessage(htmlHelper, modelMetadata.PropertyName);
			}

			RegisterScript(htmlHelper, id);
			return new MvcHtmlString(string.Format("{0}{1}", input, validation));
		}

		private static void RegisterScript(HtmlHelper htmlHelper, string id) {
			htmlHelper.AddScript(string.Format("$('#{0}').datepicker({{ changeMonth: true, changeYear: true }});", id));
		}
	}
}